package com.yfp.tissue.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.utils.uuid.Snowflake;
import com.yfp.common.datascope.annotation.DataScope;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.system.api.domain.SysUser;
import com.yfp.system.api.model.LoginUser;
import com.yfp.tissue.domain.Dto.AreaDto;
import com.yfp.tissue.domain.Dto.CompanyDto;
import com.yfp.tissue.domain.entity.*;
import com.yfp.tissue.domain.vo.AreaVO;
import com.yfp.tissue.domain.vo.CompanyVO;
import com.yfp.tissue.mapper.*;
import com.yfp.tissue.service.AreaService;
import com.yfp.tissue.domain.entity.*;
import com.yfp.tissue.mapper.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import static com.yfp.common.core.utils.PageUtils.startPage;


/**
 * @PROJECT_NAME: ydyfp
 * @DESCRIPTION:
 * @USER: xiaohuya
 * @DATE: 2023/12/15 14:13
 */

@Service
@Slf4j

public class AreaServiceImpl implements AreaService {

    @Resource
    private AreaMapper areaMapper;
    @Resource
    private MachineMapper machineMapper;

    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private DistrictMapper districtMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private PositionTypeMapper positionTypemapper;
    @Resource
    private PositionMapper positionMapper;
    @Resource
    private RouteMapper routeMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysUserCompanyMapper sysUserCompanyMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @DataScope(deptAlias = "a")
    @Override
    public List<AreaVO> queryArea(AreaDto areaDto) {
        startPage();
        List<AreaVO> areaVOS = areaMapper.queryAllByLimit(areaDto);
        return areaVOS;
    }

    @Override
    public List<AreaVO> findList(AreaDto areaDto) {
        return areaMapper.findList(areaDto);
    }

    @Override
    public R addArea(Area area) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long deptId = SecurityUtils.getLoginUser().getSysUser().getDeptId();
        String cityName = StrUtil.subBefore(area.getName(), "/", false);

        Snowflake snowflake = new Snowflake(1);
        area.setAreaId(String.valueOf(snowflake.nextId()));
        area.setUpdateName(loginUser.getSysUser().getNickName());
        area.setEnabled("1");
        area.setDeptId(deptId);
        area.setCityName(cityName);
        int insert = areaMapper.insert(area);
        return R.ok(insert);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R updateArea(Area area) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        area.setUpdateName(loginUser.getSysUser().getNickName());
        String cityName = StrUtil.subBefore(area.getName(), "/", false);
        area.setCityName(cityName);
        int insert = areaMapper.update(area);


        // 同步更新线路点位城市字段
        Route route = new Route();
        route.setAreaId(area.getAreaId());
        route.setCityName(cityName);
        routeMapper.updateByAreaId(route);

        Position position = new Position();
        position.setAreaId(area.getAreaId());
        position.setCityName(cityName);
        positionMapper.updateByAreaId(route);
        return R.ok(insert);
    }

    @Override
    public R areaDetail(String areaId) {
        Area area = areaMapper.queryCompany(areaId);
        SysUser sysUser = sysUserMapper.selectUserById(Long.parseLong(area.getContracts()));
        area.setContracts(sysUser.getNickName());
        if (area == null) {
            return R.fail("未查到相关信息");

        }
        CompanyVO companyVO = companyMapper.oneNameList(area.getCompanyId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("area", area);
        map.put("company", companyVO);

        List<AreaDto> positions = positionMapper.queryPotion(areaId);
        if (positions.size() > 0) {
            map.put("positions", positions);
        }

        // todo
        return R.ok(map);
    }

    @Override
    public R conditionsArea(String companyId) {
        List<AreaVO> areaVOS;
        if (SecurityUtils.getUsername().equals("15271848757")) {
            areaVOS = areaMapper.conditionsArea(null);
        } else {
            areaVOS = areaMapper.conditionsArea(companyId);

        }
        List<String> collect = areaVOS.stream().map(AreaVO::getCompanyName).distinct().toList();
        HashMap<String, List<AreaVO>> stringListHashMap = new HashMap<>();
        collect.forEach(e -> {
            stringListHashMap.put(e, areaVOS.stream().filter(area -> area.getCompanyName().equals(e)).toList());
        });
        return R.ok(stringListHashMap);
    }

    @Override
    public R addQuery(String companyId) {
        HashMap<String, Object> areaMap = new HashMap<>();
        List<CompanyVO> companyVOS;
        List<District> districts = null;
        List<SysUser> users = null;
        List<PositionType> positionTypes = null;
        List<Route> routes = null;
        if (true) {
            companyVOS = companyMapper.queryNameList(null);
            // 区
            List<District> countys = districtMapper.queryCounty();
            // 市
            List<District> citys = districtMapper.queryCity();
            // 省
            districts = districtMapper.queryProvince();

            citys.stream().forEach(e -> {
                List<District> list = countys.stream().filter(cs -> cs.getId().equals(e.getValue())).toList();
                e.setChildren(list);
            });
            districts.stream().forEach(e -> {
                List<District> list = citys.stream().filter(cs -> cs.getId().equals(e.getValue())).toList();
                e.setChildren(list);
            });
            routes = routeMapper.queryById(null, null);
//                查询公司全部人员
            users = sysUserMapper.queryUserList(companyId);
            positionTypes = positionTypemapper.queryPosition(null);

        } else {
            companyVOS = companyMapper.queryNameList(companyId);
            if (!companyVOS.isEmpty()) {
                CompanyVO companyVO = companyVOS.get(0);
                String district = extractCity(companyVO.getAddress());
                // 区
                List<District> countys = districtMapper.queryCounty();
                // 市
                List<District> citys = districtMapper.queryCity();
                routes = routeMapper.queryById(companyId, null);
                citys.stream().forEach(

                        e -> {
                            if (district.equals(e.getLabel())) {
                                List<District> list = countys.stream().filter(cs -> cs.getId().equals(e.getValue())).toList();
                                e.setChildren(list);
                            }

                        });
//                查询公司全部人员
                users = sysUserMapper.queryUserList(companyId);
                positionTypes = positionTypemapper.queryPosition(companyId);

            }
        }

        areaMap.put("positionTypes", positionTypes);
        areaMap.put("routes", routes);
        areaMap.put("company", companyVOS);
        areaMap.put("users", users);
        areaMap.put("district", districts);
        return R.ok(areaMap);
    }

    @Override
    @Transactional
    public R prohibit(String id, String type, String enabled) {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        SysUser sysUser = new SysUser();
        Area ar = new Area();
        Route route = new Route();
        Position position = new Position();
        Machine machine = new Machine();
        CompanyDto companyDto = new CompanyDto();
        ar.setUpdateName(loginUser.getSysUser().getNickName());
        route.setUpdateName(loginUser.getSysUser().getNickName());
        companyDto.setUpdateName(loginUser.getSysUser().getNickName());
        position.setUpdateName(loginUser.getSysUser().getNickName());
        CompanyDto company = new CompanyDto();
        company.setParentId(id);
        List<CompanyVO> companyVOS = companyMapper.queryAllByLimit(company);
        List<String> list = companyVOS.stream().map(CompanyVO::getCompanyId).toList();
        if (list.isEmpty()) {
            list = Collections.singletonList(id);
        } else {
            list.add(id);
        }
        list.forEach(e -> {
            switch (type) {
                case "公司":
                    sysUser.setCompanyId(e);
                    position.setCompanyId(e);
                    companyDto.setCompanyId(e);
                    ar.setCompanyId(e);
                    route.setCompanyId(e);
                    machine.setCompanyId(e);
                    String status = enabled.equals("0") ? "1" : "0";
                    sysUser.setStatus(status);
                    sysUserMapper.updateEnable(sysUser);
                    companyDto.setEnabled(enabled);
                    companyMapper.update(companyDto);
                    ar.setEnabled(enabled);
                    areaMapper.updateEnable(ar);
                    route.setEnable(enabled);
                    routeMapper.updateEnable(route);
                    position.setEnable(enabled);
                    positionMapper.updateEnable(position);
                    break;
                case "区域":
                    ar.setAreaId(e);
                    route.setAreaId(e);
                    position.setAreaId(e);
                    machine.setRouteId(e);
                    ar.setEnabled(enabled);
                    areaMapper.updateEnable(ar);
                    route.setEnable(enabled);
                    routeMapper.updateEnable(route);
                    position.setEnable(enabled);
                    positionMapper.updateEnable(position);
                    break;
                case "线路":

                    route.setRouteId(e);
                    machine.setRouteId(e);
                    position.setRouteId(e);
                    route.setEnable(enabled);
                    routeMapper.updateEnable(route);
                    position.setEnable(enabled);
                    positionMapper.updateEnable(position);
                    break;
                case "点位":

                    position.setPositionId(e);
                    machine.setPositionId(e);
                    position.setEnable(enabled);
                    positionMapper.updateEnable(position);
                    break;
            }


            machine.setEnable(Integer.valueOf(enabled));
            machineMapper.updateEnable(machine);
        });

        return R.ok();
    }

    @Override
    public Area getById(String areaId) {
        return areaMapper.getById(areaId);
    }


    public static String extractCity(String address) {
        String[] parts = address.split("省");
        if (parts.length > 1) {
            String cityAndDistrict = parts[1];
            String[] cityAndDistrictParts = cityAndDistrict.split("市");
            if (cityAndDistrictParts.length > 0) {
                return cityAndDistrictParts[0] + "市";
            }
        }
        return "未找到城市信息";
    }
}
